<template>
  <div class="upload-file">
    <el-upload
      multiple
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">
        <slot> 导入数据 </slot>
      </el-button>
    </el-upload>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
const props = defineProps({
  url: [String, Object, Array],
  fullPath: [String, Object, Array],
});

const { proxy } = getCurrentInstance();
const emit = defineEmits(["success"]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(
  baseUrl + (props.fullPath || props.url + "importData")
); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  return true;
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess(res.msg || "导入成功");
    emit("success", res);
  } else {
    proxy.$modal.msgError(res.msg);
  }
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
